package com.mankiw.springboot_mankiw.Controller;

import com.mankiw.springboot_mankiw.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.mankiw.springboot_mankiw.pojo.ResponseMessage;
import com.mankiw.springboot_mankiw.pojo.User;
import com.mankiw.springboot_mankiw.pojo.dto.UserDto;

@RestController//接口方法返回对象，转换成json文本
@RequestMapping("/user") //localhost:8088/user/
public class UserController {

    @Autowired//自动装配
    IUserService userService;

    //REST
    //增加用户
    //@PostMapping("/add")
    @PostMapping
    public ResponseMessage<User> add(@RequestBody UserDto user) throws Exception {//RequestBody注解将json自动转成对象
        User userNew = userService.add(user);
        if (true) {
            throw new Exception("123");
        }
        return ResponseMessage.success(userNew);
    }

    @GetMapping
    public String test() {
        return "aaa";
    }

    //查询用户
    @GetMapping("/{userId}")
    //注意参数名
    public ResponseMessage<User> get(@PathVariable Integer userId) {
        var user = userService.getUser(userId);
        return ResponseMessage.success(user);
    }
    //修改用户
    @PutMapping
    public ResponseMessage edit(@RequestBody UserDto user) throws Exception {
        var userEdit = userService.edit(user);
        return ResponseMessage.success(userEdit);
    }
    //删除用户
    @DeleteMapping("/{userId}")
    public ResponseMessage delete(@PathVariable Integer userId) throws Exception {
        userService.delete(userId);
        return ResponseMessage.success(null);
    }
}
